import axios from "axios";
import sign from "jwt-encode";
import { storageLocal } from "../storage";
// declare var AnyShareSDKFactory;
const ecmUrl = import.meta.env.VITE_ECM_URL;
const oauth2 = async () => {
  const params = {
    client_name: "epms",
    grant_types: ["authorization_code", "implicit", "refresh_token"],
    response_types: ["token id_token", "code", "token"],
    scope: "offline openid all",
    redirect_uris: ["https://127.0.0.1:9010/callback"],
    post_logout_redirect_uris: ["https://127.0.0.1:9010/successful-logout"],
    metadata: {
      device: {
        name: "eisoo测试iphone",
        client_type: "ios",
        description: "IPhone"
      }
    }
  };
  const res = await axios.post(`${ecmUrl}/oauth2/clients`, params);
  return res.data;
};

const getSSO = async (client_id, as_code) => {
  const params = {
    client_id,
    redirect_uri: "https://127.0.0.1:9010/callback",
    response_type: "token id_token",
    scope: "offline openid all",
    udids: [""],
    credential: {
      id: import.meta.env.VITE_APP_ECM_ID,
      params: {
        as_code
      }
    }
  };
  const res = await axios.post(`${ecmUrl}/api/authentication/v1/sso`, params);
  return res.data;
};

export const getAccToken = async () => {
  let ecm_params = storageLocal.getItem("ecm_params");
  const timer = new Date();
  const timestamp = timer.getTime();
  if (ecm_params && timestamp - ecm_params.timestamp < 30 * 60 * 1000) {
    storageLocal.setItem("ecm-token", ecm_params.access_token);
  } else {
    const { client_id } = await oauth2();
    const payload = {
      username: import.meta.env.VITE_APP_ECM_USER,
      exp: parseInt(timestamp / 1000) + 120
    };
    const encode = sign(payload, "eisoo.com");
    const data = await getSSO(client_id, encode);
    storageLocal.setItem("ecm-token", data.access_token);
    ecm_params = {
      client_id,
      access_token: data.access_token,
      timestamp,
      time: timer.toLocaleString()
    };
    storageLocal.setItem("ecm_params", ecm_params);
  }
};

export const setAccToken = async () => {
  await getAccToken();
  await getEntryDocLib();
};

export const getEntryDocLib = async () => {
  const res = await axios.get(`${ecmUrl}/api/efast/v1/entry-doc-lib`, {
    headers: {
      Authorization: `Bearer ${storageLocal.getItem("ecm-token")}`
    }
  });
  const data = res.data;
  const target = data.find(item => item.name === "epms测试库");
  storageLocal.setItem("ecm-doc-id", target.id);
};

export const getFolderList = async (docid: string) => {
  return await axios.post(
    `${ecmUrl}/api/efast/v1/dir/list`,
    {
      docid
    },
    {
      headers: {
        Authorization: `Bearer ${storageLocal.getItem("ecm-token")}`
      }
    }
  );
};

export const creatFolder = async (docid: string, date: string) => {
  const params = {
    docid,
    path: date
  };
  const { status, data } = await axios.post(
    `${ecmUrl}/api/efast/v1/dir/createmultileveldir`,
    params,
    {
      headers: {
        Authorization: `Bearer ${storageLocal.getItem("ecm-token")}`
      }
    }
  );
  if (status === 200) {
    return data.docid;
  }
  return "";
};

export const setEcmOnlineFolder = async (docid: string) => {
  const timer = new Date();
  const year = timer.getFullYear();
  const month = timer.getMonth() + 1;
  return await creatFolder(docid, `${year}${month < 10 ? "0" + month : month}`);
  const date = timer.toLocaleDateString();
  const dateArr = date.split("/");
  let newDocid = docid;
  let haveFolder = true;
  for (let i = 0; i < dateArr.length; i++) {
    const { data } = await getFolderList(newDocid);
    const find = data.dirs.find(val => {
      return val.name === dateArr[i];
    });
    if (find) {
      newDocid = find.docid;
    } else {
      haveFolder = false;
      break;
    }
  }
  if (haveFolder) {
    return newDocid;
  }
  return await creatFolder(docid, date);
};

export const importFileForEcm = async (docid, file) => {
  await getAccToken();
  const newDocid = await setEcmOnlineFolder(docid);
  if (!newDocid) {
    return;
  }
  const params = {
    client_mtime: parseInt(new Date().getTime() / 1000) + 120,
    docid: newDocid,
    length: file.size,
    name: file.name
  };
  const res = await axios.post(
    `${ecmUrl}/api/efast/v1/file/osbeginupload`,
    params,
    {
      headers: {
        Authorization: `Bearer ${storageLocal.getItem("ecm-token")}`
      }
    }
  );
  const id = res.data.docid;
  const rev = res.data.rev;

  await upoladFile(res.data.authrequest, file);
  await upoladFileDone(id, rev);
  return {
    docid: id,
    rev
  };
};

const upoladFile = async (authrequest, file) => {
  const Authorization = authrequest[2].split(": ");
  const ContentType = authrequest[3].split(": ");
  const xAmzDate = authrequest[4].split(": ");

  await axios({
    method: authrequest[0],
    url: authrequest[1],
    data: file,
    headers: {
      Authorization: Authorization[1],
      "Content-Type": ContentType[1],
      "x-amz-date": xAmzDate[1]
    }
  });
};

const upoladFileDone = async (docid, rev) => {
  const params = {
    docid,
    rev
  };
  const res = await axios.post(
    `${ecmUrl}/api/efast/v1/file/osendupload`,
    params,
    {
      headers: {
        Authorization: `Bearer ${storageLocal.getItem("ecm-token")}`
      }
    }
  );
  return res.data;
};

export const getFileBolb = async (docid, rev) => {
  const params = {
    docid,
    rev
  };
  const res = await axios.post(
    `${ecmUrl}/api/efast/v1/file/osdownload`,
    params,
    {
      headers: {
        Authorization: `Bearer ${storageLocal.getItem("ecm-token")}`
      }
    }
  );
  const authrequest = res.data.authrequest;
  const Authorization = authrequest[2].split(": ");
  const xAmzDate = authrequest[3].split(": ");
  const file: any = await axios({
    method: authrequest[0],
    url: authrequest[1],
    responseType: "blob",
    headers: {
      Authorization: Authorization[1],
      "x-amz-date": xAmzDate[1]
    }
  });
  return file.data;
};

export const downloadFile = async (docid, fileName) => {
  await getAccToken();
  // await getSSO()
  const params = {
    docid,
    rev: ""
  };
  const res = await axios.post(
    `${ecmUrl}/api/efast/v1/file/osdownload`,
    params,
    {
      headers: {
        Authorization: `Bearer ${storageLocal.getItem("ecm-token")}`
      }
    }
  );
  const authrequest = res.data.authrequest;
  const Authorization = authrequest[2].split(": ");
  const xAmzDate = authrequest[3].split(": ");
  const file: any = await axios({
    method: authrequest[0],
    url: authrequest[1],
    responseType: "blob",
    headers: {
      Authorization: Authorization[1],
      "x-amz-date": xAmzDate[1]
    }
  });
  const blob = new Blob([file.data]);
  const downloadURL = window.URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.download = fileName;
  a.href = downloadURL;
  document.body.appendChild(a);
  a.click();
  setTimeout(function () {
    URL.revokeObjectURL(downloadURL);
    a.remove();
  }, 1000);
};

export const previewEcmImage = async (docid, width, height) => {
  await getAccToken();
  const res = await axios.get(`${ecmUrl}/api/efast/v1/file/thumbnail`, {
    params: { docid, width, height, quality: 100 },
    responseType: "blob",
    headers: {
      Authorization: `Bearer ${storageLocal.getItem("ecm-token")}`
    }
  });

  return res.data;
};

export const previewImage = async (format, docid) => {
  await getAccToken();
  const res = await axios.post(
    `${ecmUrl}/api/open-doc/v1/file-preview`,
    {
      format,
      id: docid
    },
    {
      // params: { docid, width, height, quality: 100 },
      // responseType: "blob",
      headers: {
        Authorization: `Bearer ${storageLocal.getItem("ecm-token")}`
      }
    }
  );

  return res.data;
};
